package pacman.state;

import java.util.Hashtable;

import org.newdawn.slick.Color;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Input;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.BasicGameState;
import org.newdawn.slick.state.StateBasedGame;
import org.newdawn.slick.state.transition.FadeInTransition;
import org.newdawn.slick.state.transition.FadeOutTransition;

import pacman.level.LevelLoader;
import pacman.level.SimpleLevel;

public class Game extends BasicGameState {
    private StateBasedGame sbg;
    private GameContainer gc;
    private Hashtable<String, String> levelChain = new Hashtable<String, String>();
    private Integer levelNumber = 1;
    private SimpleLevel currentLevel;
    
    public static final int ID = 1;

    @Override
    public int getID() {
    	return ID;
    }

    public void init(GameContainer gc, StateBasedGame sbg) throws SlickException {
		this.sbg = sbg;
		this.gc = gc;
		try {
		    LevelLoader loader = new LevelLoader("resources/data/maps/levels.properties");
		    levelChain = loader.getLevelChain();
		    if (levelNumber > levelChain.size() + 900) levelNumber = 1;
		    if (levelNumber <= levelChain.size())  currentLevel = new SimpleLevel(levelChain.get(levelNumber.toString()));
		    else {
		    	levelNumber = levelNumber + 1000;
		    	sbg.enterState(EndOfGame.ID, new FadeOutTransition(Color.black), new FadeInTransition(Color.black));
		    	return;
		    }
		 } catch (Exception e) {
			 System.out.println(e.getMessage());
		 }
    }

    public void render(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException {
    	currentLevel.render(this, g);
    }

    public void update(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException {
    	currentLevel.update(gc, delta);				//Update mọi thứ bên trong Current Level
    	if (currentLevel.isLevelLose()) {					//Kiểm tra trạng thái Game là thua
    		sbg.enterState(LevelLose.ID);					//Chạy sang State LevelLose
    		init(gc, sbg);
    		return;
    	}
		if (currentLevel.isLevelEnded()) {
		    levelNumber++;
		    sbg.enterState(LevelWin.ID);
		    init(gc, sbg);
		    return;
		}
    }

    public void keyReleased(int key, char c) {
		if (key == Input.KEY_ESCAPE) {
		    sbg.enterState(Pause.ID, new FadeOutTransition(Color.black), new FadeInTransition(Color.black));
		}
		if (key == Input.KEY_F2) {
		    try {
				if (!gc.isFullscreen()) gc.setFullscreen(true);
				else gc.setFullscreen(false);
		    } catch (Exception e) {
		    	System.out.println(e.getMessage());
		    }
		}
    }
}
